<?php

namespace app\home\home;
use app\admin\controller\Admin;
use app\home\model\User;
use phpDocumentor\Reflection\DocBlock\Tags\Var_;
use think\Controller;
use think\Db;
use think\Loader;
use think\Request;
use app\common\model\AdminAnnex as AnnexModel;
class Squares extends Base
{
    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index(Request $request)
    {
        $data = $request->param();
        $id = isset($data['id']) ? $data['id'] : '';
        isset($data['type']) ? $type = $data['type'] : $type = ['in',[2,3,4]] ;
        isset($data['toid']) ? $where['uid'] = $data['toid'] : 0;
        $where['type'] = $type;
        $page = $data['page'];
        $listrow = $data['listrow'];
        if (isset($data['pics1'])){
            $picwhere =[
                'type'=>['in',[1,4]],
//                'pics1'=>'not null',
                'uid' =>$data['toid'],
            ];
            $pic = \db('home_squares')
                ->where($picwhere)
                ->field('pics1')
                ->paginate(20,true,['page'=>$data['page']]);
            $pics = [];
            foreach ($pic as $k=>$v){
                foreach (explode(',',$v['pics1']) as $i=>$j){
                    if (!empty($j)){
                        $pics[] = $j;
                    }else{
                        continue;
                    }

                }
                if (count($pics) > 3){
                    continue;
                }
            }
            return apistatus(1,'获取成功',$pics);
        }else{
            if (($data['type'] == 1) && !empty($data['id'])){
                $gender = \db('home_users')->where('id',$data['id'])->field('gender,role')->find();
                if ($gender['gender'] == 1 && $gender['role'] == 1){
                    $where['U.gender'] = 2;
                }else{
                    $where['U.gender'] = 1;
                }
            }
            $squarelist = \db('home_squares')
                ->alias('S')
                ->join('home_users U',"S.uid=U.id")
                ->field('S.id,S.uid,S.contents,S.pics1,S.type,S.skills,S.longitude,S.latitude,S.create_time,S.is_top,
            U.gender,U.nickname,U.role,U.age,U.address uaddress,S.saddress,U.operation_time,U.headicon')
                ->order('S.is_top desc,S.create_time desc')
                ->where($where)
                ->paginate($listrow,true,['page'=>$page])
                ->each(function ($item){
                    $item['countpraise'] = countPraises($item['id']);
                    if ($item['operation_time'] > (time()-300)){
                        $item['opstatus'] = '在线';
                    }else{
                        $item['opstatus'] = '离线';
                    }
                    $item['pics1'] = explode(',',$item['pics1']);
                    return $item;
                });
            $squarelist = $squarelist->toarray();
            if (!empty($squarelist)){
                if (!empty($id)){
                    $langlati = \db('home_users')
                        ->where('id',$id)
                        ->field('longitude,latitude')
                        ->find();
                }else{
                    $langlati['latitude'] = '';
                    $langlati['longitude'] = '';
                }
                foreach ($squarelist['data'] as  $k=>$v){
                    $is_praise = isPraise($data['id'],$v['id']);
                    $squarelist['data'][$k]['is_praise'] = $is_praise;
                    if (empty($langlati['latitude']) || empty($v['longitude'])){
                        $squarelist['data'][$k]['distance'] = '未知';
                        continue;
                    }
                    $distance = getDistanceKm($langlati['longitude'],$langlati['latitude'],$v['longitude'],$v['latitude']);
                    $squarelist['data'][$k]['distance'] = sprintf("%.2f", $distance);
                }
                return apistatus(1,'列表获取成功',$squarelist);
            }else{
                return apistatus(0,'无数据');
            }
        }

    }

    /**
     * 创建动态或者征婚
     *
     * @return \think\Response
     */
    public function create(Request $request)
    {
        $data = $request->param();
        $validate = validate('squares');
        $res = $validate->scene('create')->check($data);
        if (!$res){
            return apistatus(0,$validate->getError());
        }
        $t='';
        $role = \db('home_users')->where('id',$data['id'])->field('role')->find();
        $insert['uid'] = $data['id'];
        $insert['contents'] = $data['contents'];
        $insert['create_time'] = time();
        $insert['saddress'] = $data['saddress'];
        $insert['pics1'] = isset($data['pics1']) ? $data['pics1'] : '';
        isset($data['longitude']) ? $insert['longitude'] = '' : $insert['longitude'] =  $data['longitude'];
        isset($data['latitude']) ? $insert['latitude'] = '' : $insert['latitude'] =  $data['latitude'];
        isset($data['type']) ? $insert['type'] = $data['type'] : $insert['type'] = 4 ;
        if ($data['role'] == 2 || $role['role'] == 3){
            $insert['type'] == $role['role'];
            empty($data['skills']) ? true : $insert['skills'] =  $data['skills'];
        }
        if ($insert['type'] == 1){
            $cost = config('base.web_marriagecost');
            $info = \db('home_users')->where('id',$data['id'])->field('rd_coin')->find();
            if (empty($info['rd_coin']) || bccomp($info['rd_coin'],$cost,2) < 0) {
                return apistatus(1, '红豆币余额不足', ['has_coin' => 0,'cost'=>$cost]);
            }
            $costinsert = [
                'uid'=>$data['id'],
                'toid'=>$data['id'],
                'num'=>$cost,
                'create_time'=>time(),
                'cost_type'=>5,

            ];
            $t = Db::table('rd_home_coinrecord')->insertGetId($costinsert);
            if ($t){
                $userupdate = [
                    'id'=>$data['id'],
                    'rd_coin'=>bcsub($info['rd_coin'],$data['cost'],2),
                ];
            }else{
                return apistatus(0,'操作失败');
            }

        }

        $res = Db::table('rd_home_squares')->insertGetId($insert);

        if ($res){
                Db::startTrans();
                try{
                    if ($t){
                        Db::table('rd_home_users')->update($userupdate);
                    }
                    Db::table('rd_home_coinrecord')->update(['id'=>$t,'status'=>2,'sqid'=>$res]);
                    // 提交事务
                    Db::commit();
                    apistatus(1,'创建成功');
                } catch (\Exception $e) {
                    // 回滚事务
                    return apistatus(0,'操作失败');
                    Db::rollback();
                }

            return apistatus(1,'创建成功');
        }else{
            return apistatus(0,'创建失败');
        }

    }

    /**
     * 保存新建的资源
     *
     * @param  \think\Request  $request
     * @return \think\Response
     */
    public function save(Request $request)
    {
        //
    }

    /**
     * 显示指定的资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function read(Request $request)
    {
         $data = $request->param();
         if (empty($data['sqid'])){
             return apistatus(0,'缺少请求数据');
         }
         $id = isset($data['id']) ? $data['id'] : '';
         $info = \db('home_squares')->alias('S')
             ->join('home_users U','S.uid=U.id')
             ->where('S.id',$data['sqid'])
             ->field('S.id,S.uid,S.contents,S.pics1,S.type,S.skills,S.longitude,S.latitude,S.create_time,S.is_top,
            U.gender, U.headicon,U.nickname,U.age,U.address uaddress,S.saddress,U.operation_time')
             ->find();
         $count = countPraises($data['sqid']);


         if (!empty($info)){
             $info['count'] = $count;
             if (!empty($data['id'])){
                 $ispraise =  isPraise($data['id'],$data['sqid']);
                 $info['is_praise'] = $ispraise;
             }else{
                 $info['is_praise'] = 0;
             }
             $info['pics'] = explode(',',$info['pics1']);
             $skills = explode(',',$info['skills']);
             if (!empty($id)){
                 $langlati = \db('home_users')
                     ->where('id',$id)
                     ->field('longitude,latitude')
                     ->find();
             }else{
                 $langlati['latitude'] = '';
                 $langlati['longitude'] = '';
             }
             if (empty($langlati['latitude']) || empty($info['longitude'])){
                 $info['distance'] = '未知';
             }else{
                 $distance = getDistanceKm($langlati['longitude'],$langlati['latitude'],$info['longitude'],$info['latitude']);
                 $info['distance'] = sprintf("%.2f", $distance);
             }
             $dat = \db('home_taps')->where(['id'=>['in',$skills]])->field('id,name')->select();
             if ($info['operation_time'] > (time()-300)){
                 $info['opstatus'] = '在线';
             }else{
                 $info['opstatus'] = '离线';
             }
             $info['skills'] = $dat;
             return apistatus(1,'详情获取成功',$info);
         }else{
             return apistatus(0,'操作失败请重试');
         }


    }

    /**
     * 显示编辑资源表单页.
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * 保存更新的资源
     *
     * @param  \think\Request  $request
     * @param  int  $id
     * @return \think\Response
     */
    public function updatetop()
    {
        $where['top_endtime'] = ['>',time()];
        \db('home_squares')->where($where)->update(['is_top'=>0,'top_starttime'=>1,'top_endtime'=>1]);
    }

    /**
     * 删除指定资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function setTop(Request $request)
    {
        $data = $request->param();
        self::checktoken($data['id']);
        $cost = $data['cost'];
        $info = \db('home_users')->where('id',$data['id'])->field('rd_coin')->find();
        if (empty($info['rd_coin']) || bccomp($info['rd_coin'],$cost,2) < 0) {
            return apistatus(1, '红豆币余额不足', ['has_coin' => 0]);
        }
        $costinsert = [
            'uid'=>$data['id'],
            'toid'=>$data['id'],
            'topid'=>$data['topid'],
            'num'=>$cost,
            'create_time'=>time(),
            'cost_type'=>1,

        ];
        $t = Db::table('rd_home_coinrecord')->insertGetId($costinsert);
        if ($t){
            $userupdate = [
                'id'=>$data['id'],
                'rd_coin'=>bcsub($info['rd_coin'],$data['cost'],2),
            ];

            Db::startTrans();
            try{

                Db::table('rd_home_users')->update($userupdate);

                Db::table('rd_home_coinrecord')->update(['id'=>$t,'status'=>2,'sqid'=>$data['sqid']]);
                // 提交事务
                Db::commit();
                apistatus(1,'操作成功');
            } catch (\Exception $e) {
                // 回滚事务
                return apistatus(0,'操作失败');
                Db::rollback();
            }

            return apistatus(1,'操作成功');
        }else{
            return apistatus(0,'操作失败');
        }



    }





}
